import 'package:flutter/cupertino.dart';
import 'package:flutter_massage/common_lib/index.dart';
import 'package:flutter_massage/pages/message/message_bean.dart';
import 'package:flutter_massage/pages/message/message_logic.dart';
import 'package:flutter_massage/pages/message/message_utils.dart';
import 'package:flutter_massage/service/index.dart';
import 'package:flutter_massage/sqlite/db_manager.dart';
import 'package:get/get.dart';

class MessageDetailLogic extends GetxController {
  final String chatId;

  MessageDetailLogic(this.chatId);

  List<MessageBean> messageList = [];

  final ScrollController scrollController = ScrollController();
  final TextEditingController textEditingController = TextEditingController();
  final FocusNode focusNode = FocusNode();
  final ScrollController inputScrollController = ScrollController();

  @override
  void onReady() async {
    super.onReady();

    if (chatId.empty) return;
    messageList = await DbManager.getMessageList(chatId: chatId);
    update();
  }

  void sendMessage() async {
    String text = textEditingController.text.trim();
    if (chatId.empty || text.empty) return;
    MessageBean messageBean = MessageBean(
      messageId: MessageUtils.createMessageId(),
      chatId: chatId,
      fromId: MessageUtils.userKey,
      fromName: XydUserService.nickName,
      toId: '',
      toName: '',
      avatar: XydUserService.avatar,
      message: text,
      updateTime: DateTime.now().millisecondsSinceEpoch.toString(),
    );

    await DbManager.insertMessage(messageBean: messageBean);
    await DbManager.updateChatLastMessage(chatId: chatId, lastMessage: text);
    CommonObservable().publishChange(MessageLogic.keyListener);

    messageList.insert(0, messageBean);
    update();
    textEditingController.clear();
  }
}
